package com.wy17113.model.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.wy17113.controller.utils.DBConnection;
import com.wy17113.controller.utils.EncoderByMd5;
import com.wy17113.model.dao.IUserDao;
import com.wy17113.model.entity.User;
public class UserDaoImpl extends HibernateBaseDao implements IUserDao {

	@SuppressWarnings("rawtypes")
	@Override
	public Class getEntityClass() {
		return User.class;
	}

	@Override
	public String getEntityType() {
		return "User";
	}

	@SuppressWarnings("rawtypes")
	public User userLogin(String account, String password) {
		Session session = getSession(true);
		Query q = session.getNamedQuery("query_userLogin");
		q.setParameter("account", account);
		q.setParameter("pwd", EncoderByMd5.getEncoderByMd5(password));
		List res = q.list();
		User user = null;
		for (int i = 0; i < res.size(); i++) {
			user = (User) res.get(i);
		}
		return user;
	}

	public void saveUser(User user) {
		getHibernateTemplate().save(user);
	}
	
	@SuppressWarnings("rawtypes")
	public int checkAccountExist(String account) {
		Session session = getSession(true);
		Query q = session.getNamedQuery("query_checkAccountExist");
		q.setParameter("account", account);
		
		List res = q.list();
		User user = null;
		for (int i = 0; i < res.size(); i++) {
			user = (User) res.get(i);
		}
		if(user != null ){
			return 1;
		}else{
			return 0;
		}
	}

	public void delete(int flag,String id) throws SQLException {
		 String sql = "update users set dr = "+ flag +" where id = '"+ id +"'";
	     Connection conn = DBConnection.getConnection();
	     PreparedStatement stmt = conn.prepareStatement(sql);
	 
	     stmt.executeUpdate();
	     stmt.close();
	     conn.close();
	}
	
	public Session getSpringSession(){
		return getHibernateTemplate().getSessionFactory().getCurrentSession();
	}
}
